<!-- 试题列表 -->
<template>
  <div class="container">
    <!-- 头部描述 -->
    <div class="top-desc">
      <span class="black-text">{{ $t('questionLangList.desc1') }}</span>
    </div>
    <!-- 操作栏 -->
    <el-form ref="actionForm" :inline="true" label-position="right" label-width="auto" @submit.native.prevent>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('questionLangList.tags')">
            <el-select v-model="tagsData" :placeholder="$t('paperQuestionLangList.tagsTooltip')" value-key="id" filterable multiple style="width: 300px">
              <el-option v-for="item in allTagsArr" :key="item.id" :label="item.title" :value="item"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('questionLangList.keyword')">
            <el-input :placeholder="$t('questionLangList.keywordTip')" v-model="conditionForm.title"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchQuestion">{{ $t('table.search') }}</el-button>
          </el-form-item>
          <el-form-item>
            <span>注：可通过选择标签来筛选出需要的题目，标签可多选</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" @click="batchRemove">{{ $t('paperQuestionLangList.batchRemove') }}</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-row type="flex" justify="end" align="middle">
            <el-form-item>
              <el-button type="primary" @click="dialogTagsManageVisible = true">{{ $t('questionLangList.tagsManage') }}</el-button>
              <el-button type="primary" @click="openAddQuestion">{{ $t('paperQuestionLangList.loggingNewQuestion') }}</el-button>
            </el-form-item>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <!-- 列表栏 -->
    <div class="grid-content">
      <el-table v-loading="listLoading" ref="dataListRef" :key="tableKey" :data="paperQuestionList" :element-loading-text="$t('table.loadingText')" @selection-change="questionSelectChange" border fit stripe highlight-current-row>
        <el-table-column type="selection" width="50">
        </el-table-column>
        <el-table-column :label="$t('table.id')" type="index" width="50" align="center"/>
        <el-table-column :label="$t('paperQuestionLangList.question')" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.category !== 'listening'" class="subjectSpan" v-html="parseNameHtml(scope.row.groupSubjectTxt, scope.row.groupSubjectAudio)"></span>
            <span v-else>
              <audio :src="scope.row.groupSubjectAudio" controls="controls" loop="loop" preload="auto"></audio>
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('paperQuestionLangList.tag')" align="center" width="80">
          <template slot-scope="scope">
            <el-button type="text" @click="lookTags(scope.row)">{{ $t('table.look') }}</el-button>
          </template>
        </el-table-column>
        <el-table-column :label="$t('paperQuestionLangList.questionType')" align="center" prop="title" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.category !== ''">{{ questionTypeArr.find(v => v.value === scope.row.category).label }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('paperQuestionLangList.lastUpdateDate')" align="center" prop="publishedAt" width="180">
        </el-table-column>
        <el-table-column :label="$t('paperQuestionLangList.loggingPeople')" align="center" prop="nickname"/>
        <el-table-column :label="$t('table.actions')" align="center" width="260">
          <template slot-scope="scope">
            <el-button type="text" @click="updateQuestion(scope.row)">{{ $t('table.edit') }}</el-button>
            <el-button type="text" @click="removeQuestion(scope.row)">{{ $t('table.remove') }}</el-button>
            <el-button type="text" @click="goToPreview(scope.row)">{{ $t('table.preview') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination :current-page="conditionForm.page" :page-sizes="[5,10,50,100,150,200]" :page-size="conditionForm.pageSize" :total="dataTotal" background layout="total, sizes, prev, pager, next, jumper" @size-change="dataSizeChange" @current-change="dataCurrentChange"/>
      </div>
    </div>
    <!-- 查看标签 -->
    <el-dialog :title="$t('paperQuestionLangList.lookTags')" :visible.sync="dialogTagsVisible" width="600px" center>
      <tagsCom :q-id="qId" @cancelAction="cancelSaveTags" />
    </el-dialog>
    <!-- 录入新题 -->
    <el-dialog :title="$t('paperQuestionLangList.newQuestion')" :visible.sync="dialogNewQuestionVisible" width="1200px" top="60px" center>
      <newQuestionCom ref="questionNew" :paper-id="id" new-type="question" @callbackFuntion="callbackHandle"/>
    </el-dialog>
    <!-- 修改题目 -->
    <el-dialog :title="$t('paperQuestionLangList.updateQuestion')" :visible.sync="dialogUpdateQuestionVisible" width="1200px" top="60px" center>
      <updateQuestionCom ref="questionUpdate" new-type="question" :paper-id="id" @callbackFuntion="callbackHandle"/>
    </el-dialog>
    <!-- 标签管理 -->
    <el-dialog :title="$t('questionLangList.tagsManage')" width="800px" :visible.sync="dialogTagsManageVisible">
      <div class="tags-manage">
        <div class="top-title" >提示：管理全部试题标签，可对试题的标签进行新增、删除、重命名等操作(标签不支持特殊字符)</div>
        <div class="add-btn">
          <template v-if="inputVisible">
            <el-input ref="saveTagInput" v-model="addTagForm.title" class="input-new-tag" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputBlur"/>
            <label>(按回车键完成输入)</label>
          </template>
          <el-button v-else type="primary" size="small" @click="showInput">{{ $t('paperQuestionLangList.addTag') }}</el-button>
        </div>
        <div class="tag-list">
          <el-tag v-for="tag in allTagsArr" :key="tag.id" closable @click="openUpdateTag(tag)" @close="handleCloseTag(tag)">
            {{ tag.title }}
          </el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getPaperQuestion, publishPaper } from '@/api/paper'
  import { createTag, getTagList, removeTag, updateTag } from '@/api/tags'
  import { getQuestionData, removeQuestion } from '@/api/question'
  import tagsCom from '../paper/components/paperTags'
  import newQuestionCom from '../paper/components/paperNewQuestion'
  import updateQuestionCom from '../paper/components/paperUpdateQuestion'
  import { parseQuestionNameHtml } from '@/utils'
  import { cates } from '@/utils/dic'
  import { removeArray } from '@/utils'
  export default {
    name: 'PaperQuestion',
    components: {
      tagsCom,
      newQuestionCom,
      updateQuestionCom
    },
    data() {
      return {
        id: '',
        tableKey: 0,
        listLoading: false,
        conditionForm: {
          page: 1,
          pageSize: 10,
          title: '',
          labelIds: ''
        },
        dataTotal: 0,
        paperQuestionList: [],
        dialogTagsVisible: false,
        questionTypeArr: [],
        dialogNewQuestionVisible: false,
        dialogUpdateQuestionVisible: false,
        dialogTagsManageVisible: false,
        qId: '',
        selectQuestionArray: [],
        allTagsArr: [],
        tagsData: [],
        inputVisible: false,
        addTagForm: {
          title: '',
          category: 'question'
        }
      }
    },
    computed: {
      'conditionForm.labelIds': function () {
        const tagsIds = []
        this.tagsData.forEach(v => {
          tagsIds.push(v.id)
        })
        return tagsIds.join(',')
      }
    },
    created() {
      this.questionTypeArr = cates
      this.id = this.$route.query && this.$route.query.id
      this.getPageDataList()
      this.initTagsData()
    },
    methods: {
      // 初始化标签数据
      initTagsData() {
        const _this = this
        getTagList({ title: '' }).then(res => {
          _this.allTagsArr = res
        })
      },
      parseNameHtml(htmlStr, audioUrl) {
        return parseQuestionNameHtml(htmlStr, audioUrl, '')
      },
      // 添加新标签
      showInput() {
        this.inputVisible = true
        this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      // 删除标签
      handleCloseTag(tag) {
        const _this = this
        _this.$confirm('确定删除标签?', '提示', {
          confirmButtonText: this.$t('table.confirm'),
          cancelButtonText: this.$t('table.cancel'),
          type: 'warning'
        }).then(() => {
          removeTag(tag.id).then(res => {
            if (res) {
              _this.allTagsArr = removeArray(this.allTagsArr, tag)
            }
          })
        })
      },
      // 编辑标签
      openUpdateTag(tag) {
        const _this = this
        this.$prompt('请输入新的标签名称', '提示', {
          inputValue: tag.title,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: '',
          inputErrorMessage: '存在特殊字符'
        }).then(({ value }) => {
          updateTag(tag.id, { title: value }).then(res => {
            tag.title = value
            if (res) {
              _this.$message({
                message: '修改成功',
                type: 'success'
              })
            }
          })
        })
      },
      // 执行添加
      handleInputConfirm() {
        const _this = this
        let submitFlag = true
        for (let i = 0; i < _this.allTagsArr.length; i++) {
          if (_this.allTagsArr[i].title == _this.addTagForm.title) {
            submitFlag = false
            break
          }
        }
        if (!submitFlag) {
          _this.$message({
            message: '标签名称重复',
            type: 'warning'
          })
        } else {
          const loading = _this.$loading({
            lock: true,
            text: '提交中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.6)'
          })
          createTag(_this.addTagForm).then(res => {
            if (res) {
              loading.close()
              _this.$message({
                message: '添加成功',
                type: 'success'
              })
              _this.allTagsArr.push(res)
              _this.inputVisible = false
              _this.addTagForm.title = ''
            }
          }).catch(err => {
            loading.close()
            console.info(err)
          })
        }
      },
      handleInputBlur() {
        this.inputVisible = false
        this.inputValue = ''
      },
      // 获取试题列表
      getPageDataList() {
        const _this = this
        _this.listLoading = true
        getQuestionData(_this.conditionForm).then(res => {
          _this.listLoading = false
          if (res) {
            _this.paperQuestionList = res.items
            _this.dataTotal = res.total
          }
        }).catch(err => {
          _this.listLoading = false
          console.info(err)
        })
      },
      // 搜索
      searchQuestion() {
        let tagsIds = []
        this.tagsData.forEach(v => {
          tagsIds.push(v.id)
        })
        this.conditionForm.page = 1
        this.conditionForm.labelIds = tagsIds
        this.getPageDataList()
      },
      dataSizeChange(val) {
        this.conditionForm.pageSize = val
        this.getPageDataList()
      },
      // 翻页
      dataCurrentChange(val) {
        this.conditionForm.page = val
        this.getPageDataList()
      },
      // 查看标签
      lookTags(row) {
        this.qId = row.id
        this.dialogTagsVisible = true
      },
      // 取消标签保存
      cancelSaveTags() {
        this.dialogTagsVisible = false
      },
      // 打开录入新题
      openAddQuestion() {
        this.dialogNewQuestionVisible = true
        this.$nextTick(() => {
          this.$refs.questionNew.initPage()
        })
      },
      // 保存回调关闭录入新题
      callbackHandle() {
        this.dialogNewQuestionVisible = false
        this.dialogUpdateQuestionVisible = false
        this.getPageDataList()
      },
      // 打开编辑试题
      updateQuestion(row) {
        this.dialogUpdateQuestionVisible = true
        this.$nextTick(() => {
          this.$refs.questionUpdate.initPage(row)
        })
      },
      // 选择试题监听事件
      questionSelectChange(rows) {
        this.selectQuestionArray = rows
      },
      // 批量移除
      batchRemove() {
        if (this.selectQuestionArray.length === 0) {
          this.$message({
            message: '请选择要移除的试题',
            type: 'warning'
          })
        } else {
          this.$confirm('确定移除试题?', '提示', {
            confirmButtonText: this.$t('table.confirm'),
            cancelButtonText: this.$t('table.cancel'),
            type: 'warning'
          }).then(() => {
            let idArray = []
            this.selectQuestionArray.forEach(v => {
              idArray.push(v.id)
            })
            this.doBatchRemove(idArray.join(','))
          })
        }
      },
      // 移除试题
      removeQuestion(row) {
        this.$confirm('确定移除试题?', '提示', {
          confirmButtonText: this.$t('table.confirm'),
          cancelButtonText: this.$t('table.cancel'),
          type: 'warning'
        }).then(() => {
          this.doBatchRemove(row.id)
        })
      },
      // 执行移除
      doBatchRemove(ids) {
        const _this = this
        const postData = {
          ids: ids,
          _method: 'DELETE'
        }
        removeQuestion('', postData).then(res => {
          if (res) {
            _this.$message({
              message: '移除成功',
              type: 'success'
            })
            _this.getPageDataList()
          }
        })
      },
      // 发布
      publishPaperAction() {
        const _this = this
        this.$confirm('确定发布?', '提示', {
          confirmButtonText: this.$t('table.confirm'),
          cancelButtonText: this.$t('table.cancel'),
          type: 'warning'
        }).then(() => {
          publishPaper(_this.id).then(res => {
            if (res) {
              _this.$message({
                message: '发布成功',
                type: 'success'
              })
              _this.getPageDataList()
            }
          })
        })
      },
      // 试题预览
      goToPreview(row) {
        this.$router.push({
          path: '/preview/index',
          query: {
            id: row.id,
            type: 'question',
            t: +new Date()
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .top-desc {
    font-size: 16px;
    font-weight: bold;
    padding: 20px 0;
    .black-text {
      color: #333333;
    }
  }
  .subjectSpan img {
    height: 130px;
  }
  .tags-manage .top-title {
    margin-bottom: 20px;
  }
  .tags-manage .add-btn {
    display: flex;
    align-items: center;
    label {
      margin-left: 30px;
    }
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .tag-list {
    margin-top: 20px;
    .el-tag {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
</style>
